package com.huajin.codetest.lock;

/**
 * 锁粗化
 * 
 * 锁粗化是jvm在编译时会做的优化，本质就是减少加锁以及锁释放的次数
 *
 * -server：server模式会比client模式作更多的优化
 * -XX:+DoEscapeAnalysis 开启逃逸分析
 * -XX:+EliminateLocks 开启锁粗化和锁消除
 */
public class LocksTest {
	
	public static void loop1() {
		 long tsStart = System.currentTimeMillis();
		 for (int i = 0; i < 100000; i++) {
			 synchronized (LocksTest.class) {
				 System.out.println("" + i);
			 }
		 }
		 System.out.println("一共耗费：" + (System.currentTimeMillis() - tsStart) + " ms");
	}
	
	/**
	 * loop1极有可能最终经过优化变为loop2
	 */
	public static void loop2() {
		 long tsStart = System.currentTimeMillis();
		 synchronized (LocksTest.class) {
			 for (int i = 0; i < 100000; i++) {
				 System.out.println("" + i);
			 }
		 }
		 System.out.println("一共耗费：" + (System.currentTimeMillis() - tsStart) + " ms");
	}
	
	public static void main(String[] args) {
		//-- loop1和loop2运行时间几乎相同
		loop1();
		loop2();
		
		//-- append1和append2运行时间几乎相同，数量越大时间就会相差增大
		append1();
		append2();
		
		int N = 77777777;
        long t;

        {
            StringBuffer sb = new StringBuffer();
            t = System.currentTimeMillis();
            //for (int i = N; i --> 0 ;) {
            for (int i = N; i > 0 ; i--) {
                sb.append("");
            }
            System.out.println(System.currentTimeMillis() - t);
        }

        {
            StringBuilder sb = new StringBuilder();
            t = System.currentTimeMillis();
            for (int i = N; i > 0 ; i--) {
                sb.append("");
            }
            System.out.println(System.currentTimeMillis() - t);
        }

		
	}
	
	public static void append1() {
		StringBuffer stringBuffer = new StringBuffer();
		long tsStart = System.currentTimeMillis();
		for (int i = 0; i < 77777777; i++) {
			 stringBuffer.append("1");
		 }
        System.out.println("一共耗费：" + (System.currentTimeMillis() - tsStart) + " ms");
	}
	
	public static void append2() {
		StringBuilder stringBuilder = new StringBuilder();
		long tsStart = System.currentTimeMillis();
		for (int i = 0; i < 77777777; i++) {
			stringBuilder.append("1");
		 }
        System.out.println("一共耗费：" + (System.currentTimeMillis() - tsStart) + " ms");
	}

}
